#include "../../lvgl/lvgl.h"
#include "ui.h"

FILE *fp = NULL;

static lv_obj_t * kb1 = NULL; 
lv_obj_t * ta_ID = NULL;
lv_obj_t * ta_Passwd = NULL;

static int tmp_x = 0 ;
static int tmp_y = 0 ;
static int tmp_ID_x = 0 ;
static int tmp_ID_y = 0 ;

lv_obj_t * ui_page = NULL;

static void event_error(lv_event_t * e)
{
    lv_obj_t* mbox= lv_event_get_current_target(e);
    uint16_t btn_id = lv_msgbox_get_active_btn(mbox);
    if(btn_id == 0)
        lv_msgbox_close(mbox);
}

static void event_handler(lv_event_t * e)
{
    lv_obj_t* mbox= lv_event_get_current_target(e);
    uint16_t btn_id = lv_msgbox_get_active_btn(mbox);
    if(btn_id == 0)
    {
        lv_msgbox_close(mbox);
        lv_scr_load(ui_page1);
    }
}

static void ta_event_cb_1(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * ta = lv_event_get_target(e);

    if(code == LV_EVENT_FOCUSED) {

        lv_keyboard_set_textarea(kb1, ta);
        lv_obj_clear_flag(kb1, LV_OBJ_FLAG_HIDDEN);

        tmp_x = lv_obj_get_x( ta_Passwd ) ;
        tmp_y = lv_obj_get_y( ta_Passwd ) ;
        tmp_ID_x = lv_obj_get_x( ta_ID ) ;
        tmp_ID_y = lv_obj_get_y( ta_ID ) ;
        // 设置输入框悬浮于键盘的上方
        lv_obj_align_to(  ta_Passwd , kb1 ,  LV_ALIGN_OUT_TOP_MID , 0 , -20 );
        lv_obj_align_to(  ta_ID , ta_Passwd ,  LV_ALIGN_OUT_TOP_MID , 0 , -20 );
    }

    if(code == LV_EVENT_DEFOCUSED) {
        lv_keyboard_set_textarea(kb1, NULL);
        lv_obj_add_flag(kb1, LV_OBJ_FLAG_HIDDEN);

        lv_obj_set_x( ta_Passwd , tmp_x );
        lv_obj_set_y( ta_Passwd , tmp_y );
        lv_obj_set_x( ta_ID , tmp_ID_x );
        lv_obj_set_y( ta_ID , tmp_ID_y );

    }
}

static void LongInFunc(lv_event_t * e)
{
    FILE* file = fopen("users.csv", "r");
    if (!file) {
        printf("无法打开文件\n");
        return;
    }

    static const char * btns[] = {"确认", ""};
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        // 去掉换行符
        line[strcspn(line, "\r\n")] = '\0';

        // 分割字符串
        char* saveptr = NULL;
        char* storedID = strtok_r(line, ",", &saveptr);
        char* storedPasswd = (storedID != NULL) ? strtok_r(NULL, ",", &saveptr) : NULL;

        if (storedID && storedPasswd &&
            strcmp(lv_textarea_get_text( ta_ID ), storedID) == 0 &&
            strcmp(lv_textarea_get_text( ta_Passwd ), storedPasswd) == 0) {

            fclose(file);

            time_t raw_time = time(NULL);              // 获取时间戳
            struct tm *local_time = localtime(&raw_time);   // 转换为本地时间结构体
            //格式化时间字符串
            char time_str[64];
            strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", local_time);
            //写入文件
            fprintf(fp, "[%s] 账号:%s\t密码:%s\t登录成功\n", time_str, lv_textarea_get_text( ta_ID ), lv_textarea_get_text( ta_Passwd ));
            //刷新缓冲区（确保立即写入磁盘）
            fflush(fp);

            // 调用其他页面初始化函数
            Page_1();
            Page_2();
            Page_3();
            Page_4();
            keyInit();
            user_value_init();

            lv_obj_t * mbox = lv_msgbox_create(NULL, "恭喜您", "登录成功" , btns , false);
            lv_obj_set_size(mbox , 400 , 200);
            lv_obj_add_style(mbox, &style_32, 0);
            lv_obj_center(mbox);

            lv_obj_add_event_cb(mbox, event_handler, LV_EVENT_VALUE_CHANGED, NULL);
            return;
        }
    }

    fclose(file);
    lv_obj_t * mbox1 = lv_msgbox_create(NULL, "登录失败", "账号或密码错误" , btns , false);
    lv_obj_set_size(mbox1 , 400 , 200);
    lv_obj_add_style(mbox1, &style_32, 0);
    lv_obj_center(mbox1);
    lv_obj_add_event_cb(mbox1, event_error, LV_EVENT_VALUE_CHANGED, NULL);

    lv_textarea_set_text(ta_ID, "");
    lv_textarea_set_text(ta_Passwd, "");

    return;  
}

void Page()
{
    CN_Freetype();

    //打开日志文件
    fp = fopen("./log.txt", "a+");
    if (fp == NULL) {
        perror("文件打开失败");
        return;
    }

    // 确保文件指针在文件末尾（追加写入）
    fseek(fp, 0, SEEK_END);

    ui_page = lv_scr_act();
    lv_obj_set_style_text_font(ui_page , &lv_font_montserrat_32 , 0 );

    lv_obj_t * title = lv_label_create(ui_page);
    lv_obj_set_width(title, lv_pct(50));
    lv_obj_set_height(title, lv_pct(15));
    lv_obj_set_y(title, lv_pct(10));
    lv_obj_set_align(title , LV_ALIGN_TOP_MID);
    lv_obj_add_style(title, &style_50, 0);
    lv_label_set_text(title, "用户登录界面");

    ta_ID = lv_textarea_create(ui_page);
    lv_obj_align(ta_ID, LV_ALIGN_CENTER , 0, -100);
    lv_textarea_set_one_line(ta_ID , true );
    lv_textarea_set_placeholder_text(ta_ID, "ID");
    lv_obj_set_size(ta_ID, 400, 50);
    lv_obj_add_event_cb(ta_ID, ta_event_cb_1, LV_EVENT_ALL, kb1);
    

    ta_Passwd = lv_textarea_create(ui_page);
    lv_obj_align_to(ta_Passwd, ta_ID , LV_ALIGN_OUT_BOTTOM_MID , -70, 50);
    lv_textarea_set_one_line(ta_Passwd , true );
    lv_textarea_set_password_mode(ta_Passwd , true );
    lv_textarea_set_placeholder_text(ta_Passwd, "PassWord");
    lv_obj_set_size(ta_Passwd, 400, 50);
    lv_obj_add_event_cb(ta_Passwd, ta_event_cb_1, LV_EVENT_ALL, kb1);

    lv_obj_t * btn_LogIn =  lv_btn_create(  ui_page );
    lv_obj_align_to(  btn_LogIn , ta_Passwd ,  LV_ALIGN_OUT_BOTTOM_MID , -100 , 60 );
    lv_obj_set_size( btn_LogIn , 200 , 50 );
    lv_obj_add_event_cb( btn_LogIn ,  LongInFunc ,  LV_EVENT_CLICKED , NULL );


    lv_obj_t * label = lv_label_create ( btn_LogIn );
    lv_obj_center( label );
    lv_label_set_text(  label , "Lon In" );

    kb1 = lv_keyboard_create(ui_page);
    lv_obj_add_flag(kb1, LV_OBJ_FLAG_HIDDEN);

}